# -*- coding: utf-8 -*-

from posixpath import join as pjoin

from django import forms
from django.utils.safestring import mark_safe
from django.contrib.admin.widgets import AdminTextareaWidget
from django.core.urlresolvers import reverse

from djmarkitup import settings, renderers
from djmarkitup.utils import absolute_url


MIU_JS = u"""
<script type="text/javascript">
(function($) {
    $(document).ready(function() {
        $('#%(id)s').markItUp(my%(default_set)sSettings);
    });
})(jQuery);
</script>
"""

SWITCHER = u"""
<input type="hidden" id="%(id)s" name="%(name)s" value="%(miu_set)s" />
<script type="text/javascript">
(function($) {
    $(document).ready(function() {
        my%(set_upper)sSettings['previewParserPath'] = '%(preview_url)s';
        $('#id_%(field_name)s').markItUp(my%(set_upper)sSettings);
        $('#switcher li').click(function() {
            $('#switcher li').removeClass('currentSet');
            newSet = $(this).attr('class');
            $(this).addClass('currentSet');
            $('#%(id)s').val(newSet);
            $('#id_%(field_name)s').markItUpRemove();
            switch(newSet) {
                %(case)s
            }
            return false;
        });
    });
})(jQuery);
</script>
"""


class DjMarkItUpWidget(forms.Textarea):

    def __init__(self, attrs=None, markitup_skin=settings.DJMIU_DEFAULT_SKIN,
                 standalone=False):
        self.miu_set = settings.DJMIU_DEFAULT_MARKUP
        self._skin = markitup_skin
        self.standalone = standalone
        self.miu_skin = absolute_url(pjoin('markitup/skins', self._skin))
        self.choices = renderers.DJMIU_MARKUP_CHOICES
        super(DjMarkItUpWidget, self).__init__(attrs)

    @property
    def media(self):
        css = dict(screen=[pjoin(self.miu_skin, 'style.css')] +
            [absolute_url(pjoin('markitup/sets', x[0], 'style.css')) for x in
             self.choices])
        if settings.DJMIU_PYGMENTS_STYLE:
            css['screen'].append(absolute_url(
                'djmarkitup/pygments_{0}.css'.format(
                settings.DJMIU_PYGMENTS_STYLE)))
        js = [
            absolute_url(settings.DJMIU_JQUERY_URL),
            absolute_url('djmarkitup/csrf.js'),
            absolute_url('markitup/jquery.markitup.js'),
        ] + [absolute_url('markitup/sets/%s/set.js' % x[0]) for x in
            self.choices]
        return forms.Media(css=css, js=js)

    def render(self, name, value, attrs=None):
        html = super(DjMarkItUpWidget, self).render(name, value, attrs)
        if self.standalone:
            html += MIU_JS % {'id': attrs['id'],
                'default_set': self.miu_set.capitalize()}
        return mark_safe(html)


class DjMarkupSelectWidget(forms.HiddenInput):

    def __init__(self, attrs=None, markup_field_name=None):
        self.miu_set = settings.DJMIU_DEFAULT_MARKUP
        self.markup_field_name = markup_field_name or u'markup_text'
        self.choices = renderers.DJMIU_MARKUP_CHOICES
        super(DjMarkupSelectWidget, self).__init__()

    @property
    def media(self):
        return forms.Media(css=dict(screen=[
            absolute_url('djmarkitup/djmarkitup.css')]))

    def render(self, name, value, attrs=None):
        value = value or self.miu_set
        html = [u'<ul id="switcher">']
        for cl, na in self.choices:
            if cl == value:
                cl += u' currentSet'
            html.append(u'  <li class="{0}">'.format(cl))
            html.append(u'    <a href="#">{0}</a>'.format(na))
            html.append(u'  </li>')
        html.append(u'</ul>')
        vals = {'miu_set': value, 'id': attrs['id'], 'name': name,
                'field_name': self.markup_field_name,
                'set_upper': value.capitalize(),
                'preview_url': reverse('djmarkitup-preview', args=[value])}
        case = []
        for cl, _ in self.choices:
            case.append(u"""\
                case '{miu_set}':
                    $("#id_{field_name}").markItUp(my{set_upper}Settings);
                    break;
                """.format(miu_set=cl, field_name=self.markup_field_name,
                           set_upper=cl.capitalize())
            )
        vals['case'] = u''.join(case)
        html.append(SWITCHER % vals)
        return mark_safe(u'\n'.join(html))


class DjAdminMarkItUpWidget(DjMarkItUpWidget, AdminTextareaWidget):
    pass
